<template>
  <div>
    <!-- 1.导航面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path: '/dashBook'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item >学员信息管理</el-breadcrumb-item>
      <el-breadcrumb-item >学员信息管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 10px;">
      <!--  1.模糊查询  -->
      <el-form :model="queryGrade" :inline="true" style="width: 60%" size="small">
        <el-form-item label="年级名称:">
          <el-input v-model="queryGrade.gradeName" placeholder="请输入需要查询的年级名次"
                    clearalble @clear="getGradeList" @keyup.enter.native="getGradeList"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" class="el-icon-refresh-left" plain @click="resetForm">重置</el-button>
          <el-button type="primary" class="el-icon-search" plain @click="getGradeList">查询</el-button>
        </el-form-item>
      </el-form>
      <div >
        <el-button size="small" type="success" class="el-icon-folder-add" plain @click="showAddDialog">新增</el-button>
        <el-button size="small" type="danger" class="el-icon-delete" plain @click="deleteByGradeIds">批量删除</el-button>
        <el-button size="small" class="el-icon-download" plain>导出</el-button>
      </div>
      <!--  2.列表 table
      @selection-change="handleSelectionChange" 需要使用一个函数或者方法去获取选中的值
      -->
      <el-table :data="gradeList" border stripe style="width: 70%;margin-top: 20px;"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column> <!-- 选项框 -->
        <el-table-column label="年级编号" prop="gradeId" width="120"></el-table-column>
        <el-table-column label="年级名称">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>年级名次:{{scope.row.gradeName}}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{scope.row.gradeName}}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>备注:{{scope.row.remarks}}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{scope.row.remarks}}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="success" class="el-icon-folder-add" plain @click="showupdateDialog(scope.row.gradeId)">编辑</el-button>
            <el-button size="small" type="danger" class="el-icon-delete" plain  @click="deleteGradeById(scope.row.gradeId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--  3.分页  -->
      <el-pagination
        style="margin-top: 15px;"
        background
        :current-page="queryGrade.pageNum"
        :page-size="queryGrade.pageSize"
        :page-sizes="[5,10,20,30]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="changePageSize"
        @current-change="changePageNum"
      ></el-pagination>
      <!--  3.新增和编辑  -->
      <el-dialog :title="gradeTitle" :visible.sync="addOrUpdateDialog" style="width: 70%">
        <span>
          <el-form size="small" :model="gradeForm" label-width="110px" :rules="gradeFormRules" ref="gradeForm">
            <el-form-item label="年级名称：" prop="gradeName">
              <el-input type="text" v-model="gradeForm.gradeName" placeholder="请输入年级名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="备注：">
              <el-input type="textarea" v-model="gradeForm.remarks" placeholder="请输入说明" clearable></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button type="info" class="el-icon-circle-close" plain size="small" @click="cancelForm">取消</el-button>
          <el-button type="success" class="el-icon-edit-outline" plain size="small" @click="saveGradeInfo">保存</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>

</template>

<script>
export default {
  name: "GradeManage",
  data(){
    return {
      gradeFormRules:{
        gradeName:[
          {required:true,message:'请输入年级名称',trigger:'blur'},
          {min:2,max:20,message: "请输入长度为2-20位字符",trigger: 'blur'}
        ]
      },
      total:0,
      gradeTitle:'',
      gradeList:[],
      queryGrade:{
        pageNum: 1, //页码
        pageSize: 5, // 每页显示多少条
        gradeName: '',// 按照年级名称去查询
      },
      greadSet:[],
      gradeForm:{
        gradeId:'',
        gradeName: '',
        remarks: ''
      },
      addOrUpdateDialog: false,
    }
  },
  /*vue 生命周期函数*/
  created(){
    //当我们的页面在浏览器上面被创建的时候需要调用created()方法
    this.getGradeList() //抽象方法 结构没有大括号
  },
  methods:{
    cancelForm(){
      this.$refs['gradeForm'].clearValidate();
      this.gradeForm = {}
      this.addOrUpdateDialog = false;
    },
    async deleteGradeById(gradeId){
      if (gradeId){
        const conf = await this.$confirm("您确定要删除此数据吗？",{
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:'warning'
        }).catch(() =>{
          this.$message({
            type:"error",
            message: "已取消此操作"
          })
        })
        if(conf === "confirm"){
          const {data:res} = await this.$http.delete('grade/delete/'+gradeId)
          console.log(res)
          if (res.success){
            this.$message.success("数据删除成功！")
            // 2.重新加载列表
            this.getGradeList()
          }else {
            this.$message.error(res.data.errorMsg)
          }
        }
      }
    },
    showupdateDialog(gradeId){
      // 查询并且回显到弹框里面
      this.$http.get('/grade/edit/'+gradeId).then(res =>{
        if(res.data.success){
          this.gradeForm = res.data.data
        }else{
          this.$message.error("查无此数据！")
        }
      })
      this.addOrUpdateDialog = true;
    },
    saveGradeInfo(){
      this.$refs.gradeForm.validate(valid =>{
        if(valid){ // valid为true 代表表单必填校验通过
          if(this.gradeForm.gradeId){
            // 就走更新操作
            this.updateGrade();
          }else {
            // gradeId为空就去保存数据到表：c_geade中
            this.saveGrade();
          }
        }else{
          this.$message.error("必填项不能为空，请重新输入！")
        }
      })
    },
    updateGrade(){
      this.$http.put('/grade/update/'+this.gradeForm.gradeId,this.gradeForm).then(res =>{
        if(res.data.success){
          // 1.保存成功提示
          this.$notify({
            title: "操作成功",
            message: "年级信息更新成功",
            type: "success"
          })
          // 2.关闭对话框
          this.addOrUpdateDialog = false
          // 3.重新加载列表
          this.getGradeList()
        }else{
          this.$message.error("年级信息保存失败:",res.data.errorMsg)
        }
      })
    },
    saveGrade(){
      this.$http.post('/grade/add',this.gradeForm).then(res =>{
        if(res.data.success){
          this.$message.success("保存数据成功")
          this.addOrUpdateDialog = false
          this.getGradeList()
        }else{
          this.$message.error("保存数据失败：{}",res.data.errorMsg)
        }
      })
    },
    showAddDialog(){
      this.gradeTitle = '新增年级信息'
      this.gradeForm = {}
      this.addOrUpdateDialog = true
    },
    async  deleteByGradeIds(){
      if(this.greadSet.length>0){
        const con = await this.$confirm('此操作将永久删除选中的数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        if(con === 'confirm'){
          // 点击确定  进来
          for (var gread of this.greadSet) {
            //console.log(gread.gradeId)
            const {data: res} = await this.$http.delete('/grade/delete/'+gread.gradeId)
            if(!res.success){
              this.$message.error("删除数据失败：{}",res.data.errorMsg)
            }
          }
          this.$notify({
            title: '操作成功',
            message: '删除数据成功',
            type: 'success'
          })
          this.getGradeList()
        }
      }
    },
    resetForm(){
      // 重置按钮操作就是将  查询框里面的内容清空
      this.queryGrade.gradeName = ""
      // 重置完了,需要重新查询一遍数据
      this.getGradeList()
    },

    changePageSize(newPageSize){ // 切换每页显示多少多少条的操作方法
      this.queryGrade.pageSize = newPageSize
      this.getGradeList();
    },
    changePageNum(newPageNum){ // 点击不同页码数调用函数(操作方法)
      this.queryGrade.pageNum = newPageNum
      this.getGradeList()
    },

    handleSelectionChange(value){
      // 将选中的值复制给 数组
      this.greadSet = value
      console.log("获取复选框选中的值：{}",this.greadSet)
    },
    // 实现方法,里面包裹的是具体操作步骤 结构用大括号包裹起来
    async getGradeList(){
      const {data : res} = await this.$http.get('/grade/findList',{params: this.queryGrade})
      if(res.success){ // 发起http  get请求,成功响应返回数据
        console.log("年级管理"+res)
        this.gradeList = res.data.rows;
        this.total=res.data.total
        //this.total = res.data.total;
      }else{
        this.$message.error("查无此数据!",res.errorMsg)
      }
      //1.
      //2.
      //3.
    },
  }
}
</script>

<style scoped>

</style>
